﻿using MediatR;
using Newtonsoft.Json;
using S.Common.EditReproductivePresenceStateHelper;
using S.Common.EditWanderStateHelper;
using S.Common.helper;
using S.Parturition.API.Application.Command;
using S.Parturition.API.Dto;
using S.Parturition.Domain;
using S.Parturition.Domain.Model;
using S.Parturition.Infrastructure.Interface;

namespace S.Parturition.API.Application.CommandHandlers
{
    /// <summary>
    /// 删除种母分娩具体实现
    /// </summary>
    public class DeleteParturitionHandler : IRequestHandler<DeleteParturitionCommand, bool>
    {

        private readonly IParturitionRepository repository;

        private readonly MyDbContext dbContext;

        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public DeleteParturitionHandler(IParturitionRepository repository, MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.repository = repository;
            this.dbContext = dbContext;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }

        public async Task<bool> Handle(DeleteParturitionCommand request, CancellationToken cancellationToken)
        {
            string Gateway = configuration.GetValue<string>("Gateway"); //获取到网关地址

            //获取到所有要删除的分娩信息
            List<ParturitionModel> ParturitionItem = repository.GetAllAsync().Result.Where(x => request.ParturitionIds.Contains(x.ParturitionId.ToString())).ToList();

            //使用事物
            using (var tran = dbContext.Database.BeginTransaction())
            {
                try
                {
                    //循环批量删除的数据
                    foreach (var item in ParturitionItem)
                    {
                        repository.DeleteAsync(item.ParturitionId);  //删除分娩信息

                        #region 修改种母历史记录

                        EditBreed editBreed = new EditBreed();

                        editBreed.EarTag = item.EarTag;

                        //反填种母历史记录
                        var jsonString = HttpClientHelper.PostResponseKey($"{Gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
                        //将获取到的种母历史记录序列化
                        var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                        if (response.WeaningDate != null)
                        {
                            tran.Rollback();
                            return false;
                        }

                        //修改种母历史记录

                        //修改分娩的信息
                        response.DeliveryDate = null;
                        response.CurrentPregnancy--;
                        response.IsEditor = true;
                        //修改种母历史记录
                        HttpClientHelper.PutDataResponse($"{Gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                        #endregion

                        #region 修改档案信息

                        //修改档案信息
                        EditReproductivePresenceState.UpdateReproductivePresenceState(item.EarTag, 1, 7, DateTime.Now, Gateway);
                        //修改流转状态
                        EditWanderState.EditWander(item.EarTag, 3, Gateway);

                        #endregion

                        #region 删除转舍信息

                        HttpClientHelper.DeleteResponse($"{Gateway}/transset/api/TransFer/DeleteSheepTransFer?EarTag=" + item.EarTag + "&SurrenderDate=" + item.DeliveryDate);

                        #endregion

                        #region 修改妊检表字段

                        HttpClientHelper.PostResponse($"{Gateway}/PregnancySet/api/PregnancyTest/UpdateSheepState?EarTag=" + item.EarTag + "", "");

                        #endregion

                    }

                    //事物提交
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    return false;
                }
            }
        }
    }
}
